package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.DyAnchorPhotoBo;
import com.ruoyi.system.domain.bo.DyClientBo;
import com.ruoyi.system.domain.bo.DyGoodsBo;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyClientAnchorBo;
import com.ruoyi.system.service.IDyClientAnchorService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户关联主播Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-02
 */
@RequiredArgsConstructor
@Service
public class DyClientAnchorServiceImpl implements IDyClientAnchorService {

    private final DyClientAnchorMapper baseMapper;
    private final DyAnchorPhotoDetailMapper dyAnchorPhotoDetailMapper;
    private final DyGoodsMapper dyGoodsMapper;
    private final DyAnchorPhotoMapper dyAnchorPhotoMapper;
    private final DyClientMapper dyClientMapper;
    private final DyClientAnchorMapper dyClientAnchorMapper;

    /**
     * 查询用户关联主播
     */
    @Override
    public DyClientAnchorVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户关联主播列表
     */
    @Override
    public TableDataInfo<DyClientAnchorVo> getClientAnchorList(DyClientAnchorBo bo, PageQuery pageQuery) {

        DyClient client = dyClientMapper.selectById(bo.getClientId());
        if (client == null){
            throw new ServiceException("用户数据为空");
        }

        Page<DyClientAnchorVo> result = baseMapper.selectVoPage(pageQuery.build(),
                new QueryWrapper<DyClientAnchor>().lambda()
                        .eq(DyClientAnchor::getClientId, client.getId())
                        .eq(DyClientAnchor::getBuyType, 0)
                        .orderByDesc(BaseEntity::getCreateTime));

        if (CollUtil.isNotEmpty(result.getRecords())){
            for (DyClientAnchorVo record : result.getRecords()) {

                DyGoods goods = dyGoodsMapper.selectOne(new QueryWrapper<DyGoods>().lambda().eq(DyGoods::getAnchorId, record.getAnchorId()).orderByDesc(BaseEntity::getCreateTime).last(" limit 1"));
                if (goods != null){
                    record.setAnchorImg(goods.getImg());
                    record.setAnchorTitle(goods.getName());
                    record.setFaceImg(goods.getFaceImg());
                }
            }
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询用户关联主播列表
     */
    @Override
    public List<DyClientAnchorVo> queryList(DyClientAnchorBo bo) {
        LambdaQueryWrapper<DyClientAnchor> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyClientAnchor> buildQueryWrapper(DyClientAnchorBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyClientAnchor> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getClientId() != null, DyClientAnchor::getClientId, bo.getClientId());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), DyClientAnchor::getRealName, bo.getRealName());
        lqw.eq(bo.getAnchorId() != null, DyClientAnchor::getAnchorId, bo.getAnchorId());
        lqw.like(StringUtils.isNotBlank(bo.getAnchorName()), DyClientAnchor::getAnchorName, bo.getAnchorName());
        lqw.eq(bo.getAnchorPhotoId() != null, DyClientAnchor::getAnchorPhotoId, bo.getAnchorPhotoId());
        lqw.eq(StringUtils.isNotBlank(bo.getDes()), DyClientAnchor::getDes, bo.getDes());
        return lqw;
    }

    /**
     * 新增用户关联主播
     */
    @Override
    public Boolean insertByBo(DyClientAnchorBo bo) {
        DyClientAnchor add = BeanUtil.toBean(bo, DyClientAnchor.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户关联主播
     */
    @Override
    public Boolean updateByBo(DyClientAnchorBo bo) {
        DyClientAnchor update = BeanUtil.toBean(bo, DyClientAnchor.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DyClientAnchor entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户关联主播
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<DyAnchorPhotoDetailVo> getClientAnchorInfo(DyClientAnchorBo bo, PageQuery pageQuery) {

        if (bo.getId() == null){
            throw new ServiceException("查询参数为空");
        }

        DyAnchorPhoto anchorPhoto = dyAnchorPhotoMapper.selectById(bo.getId());

        Page<DyAnchorPhotoDetailVo> page = dyAnchorPhotoDetailMapper.selectVoPage(pageQuery.build(),
                new QueryWrapper<DyAnchorPhotoDetail>().lambda().eq(DyAnchorPhotoDetail::getAnchorPhotoId, anchorPhoto.getId()).orderByDesc(BaseEntity::getCreateTime));

        return TableDataInfo.build(page);
    }

    @Override
    public TableDataInfo<DyAnchorPhotoVo> getClientAnchorAlbumList(DyClientAnchorBo bo, PageQuery pageQuery) {

        DyClientAnchor clientAnchor = baseMapper.selectById(bo.getId());
        if (clientAnchor == null){
            throw new ServiceException("查询为空");
        }

        Page<DyAnchorPhotoVo> voPage = dyAnchorPhotoMapper.selectVoPage(pageQuery.build(),
                new LambdaQueryWrapper<DyAnchorPhoto>().eq(DyAnchorPhoto::getAnchorId, clientAnchor.getAnchorId()).orderByDesc(DyAnchorPhoto::getNewestTime));

        if (CollUtil.isNotEmpty(voPage.getRecords())){
            for (DyAnchorPhotoVo record : voPage.getRecords()) {
                List<DyAnchorPhotoDetail> details = dyAnchorPhotoDetailMapper.selectList(new QueryWrapper<DyAnchorPhotoDetail>().lambda().eq(DyAnchorPhotoDetail::getAnchorPhotoId, record.getId()).orderByDesc(BaseEntity::getCreateTime));
                record.setDetails(details);
            }
        }

        return TableDataInfo.build(voPage);
    }

    /**
     * 查询推荐列表
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<DyGoodsVo> getRecommendPage(DyGoodsBo bo, PageQuery pageQuery) {

        LoginUser user = LoginHelper.getLoginUser();
        if (user == null){
            throw new ServiceException("当前未登录");
        }

        IPage<DyGoodsVo> iPage = dyGoodsMapper.selectVoPage(pageQuery.build(), new LambdaQueryWrapper<DyGoods>().orderByDesc(BaseEntity::getCreateTime));

        if (CollUtil.isNotEmpty(iPage.getRecords())){

            Long userId = user.getUserId();

            List<Long> anchorIds = new ArrayList<>();

            List<DyClientAnchor> anchors = dyClientAnchorMapper.selectList(new LambdaQueryWrapper<DyClientAnchor>().eq(DyClientAnchor::getClientId, userId).eq(DyClientAnchor::getBuyType, 0));
            anchorIds = anchors.stream().map(DyClientAnchor::getAnchorId).collect(Collectors.toList());

//            List<Long> longs = iPage.getRecords().stream().map(DyGoodsVo::getAnchorId).collect(Collectors.toList());
//            List<DyAnchorPhoto> photos = dyAnchorPhotoMapper.selectList(new LambdaQueryWrapper<DyAnchorPhoto>().in(DyAnchorPhoto::getAnchorId, longs));

            for (DyGoodsVo record : iPage.getRecords()) {

                boolean isbuy = false;
                Date time = new Date();

                if (anchorIds.contains(record.getAnchorId())){
                    isbuy = true;
                }

                record.setIsBuy(isbuy);

                DyAnchorPhoto photo = dyAnchorPhotoMapper.selectOne(new LambdaQueryWrapper<DyAnchorPhoto>().eq(DyAnchorPhoto::getAnchorId, record.getAnchorId()).orderByDesc(DyAnchorPhoto::getNewestTime).last(" limit 1"));
                if (photo != null){
                    time = photo.getNewestTime();
                }

                record.setNewestTime(time);
            }
        }

        return TableDataInfo.build(iPage);
    }

    @Override
    public TableDataInfo<DyAnchorPhotoVo> getNewPhotosPage(DyAnchorPhotoBo bo, PageQuery pageQuery) {

        LoginUser user = LoginHelper.getLoginUser();
        if (user == null){
            throw new ServiceException("当前未登录");
        }

        IPage<DyAnchorPhotoVo> iPage = dyAnchorPhotoMapper.selectVoPage(pageQuery.build(), new LambdaQueryWrapper<DyAnchorPhoto>().orderByDesc(DyAnchorPhoto::getNewestTime));
        if (CollUtil.isNotEmpty(iPage.getRecords())){

            Long userId = user.getUserId();
            String limit = " limit 2";
            List<Long> anchorIds = new ArrayList<>();

            List<DyClientAnchor> anchors = dyClientAnchorMapper.selectList(new LambdaQueryWrapper<DyClientAnchor>().eq(DyClientAnchor::getClientId, userId).eq(DyClientAnchor::getBuyType, 1));
            anchorIds = anchors.stream().map(DyClientAnchor::getAnchorId).collect(Collectors.toList());

            for (DyAnchorPhotoVo record : iPage.getRecords()) {

                if (anchorIds.contains(record.getAnchorId())){
                    record.setIsBuy(true);
                    List<DyAnchorPhotoDetail> details = dyAnchorPhotoDetailMapper.selectList(new LambdaQueryWrapper<DyAnchorPhotoDetail>().eq(DyAnchorPhotoDetail::getAnchorId, record.getAnchorId()).orderByDesc(BaseEntity::getCreateTime));
                    record.setDetails(details);
                }
                else {
                    record.setIsBuy(false);
                    List<DyAnchorPhotoDetail> details = dyAnchorPhotoDetailMapper.selectList(new LambdaQueryWrapper<DyAnchorPhotoDetail>().eq(DyAnchorPhotoDetail::getAnchorId, record.getAnchorId()).orderByDesc(BaseEntity::getCreateTime).last(limit));
                    record.setDetails(details);
                }
            }
        }

        return TableDataInfo.build(iPage);
    }

    @Override
    public TableDataInfo<DyAnchorPhotoVo> getRecommendDetailPage(DyGoodsBo bo, PageQuery pageQuery) {

        LoginUser user = LoginHelper.getLoginUser();
        if (user == null){
            throw new ServiceException("当前未登录");
        }

        if (bo.getId() == null){
            throw new ServiceException("查询参数不全");
        }

        DyGoods goods = dyGoodsMapper.selectById(bo.getId());
        if (goods == null){
            throw new ServiceException("主播数据不存在");
        }

        //查验是否购买
        Long userId = user.getUserId();
        DyClientAnchor anchor = dyClientAnchorMapper.selectOne(new LambdaQueryWrapper<DyClientAnchor>().eq(DyClientAnchor::getClientId, userId).eq(DyClientAnchor::getAnchorId, goods.getAnchorId()));
        if (anchor == null){
            throw new ServiceException("当前主播数据未购买");
        }

        return getClientAnchorAlbumList(BeanUtil.toBean(anchor, DyClientAnchorBo.class), pageQuery);
    }

}
